package com.itheima.config;







import com.alibaba.fastjson.JSON;
import com.itheima.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

////@Slf4j
//@Component
////filterName属性表示filter的名称，urlPatter表示要拦截的URL资源
//@WebFilter(urlPatterns = "/*", filterName = "isLoginFilter")
public class isLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将servlet转为HttpServlet
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //2.获取本次请求的URI   "/backend/index.html"
        String uri = req.getRequestURI();
//        int i = uri.lastIndexOf("/");
//        //判断本次请求, 是否需要登录, 才可以访问
//
//        String result = uri.substring(i+1);
//        String[] split = result.split("\\.");
//        if("login".equals(split[0]) || "logout".equals(split[0])){
//            //如果不需要，则直接放行
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }


        //判断登录状态，如果已登录，则直接放行
            //使用Spring中的路径匹配的
        AntPathMatcher antPathMatcher = new AntPathMatcher();
            //定义要放行的资源
        String[] pass ={"/backend/**","/front/**","/employee/login"};
        for (String s : pass) {
            boolean match = antPathMatcher.match(s,uri);
            if (match){
                //放行
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }


        HttpSession session = req.getSession();
        Object employee = session.getAttribute("Employee");
        if(employee!=null){
            //已登录,放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //如果未登录, 则返回未登录结果
        //通过json字符串响应数据
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(JSON.toJSONString(Result.error("notLogin")));
        return;

    }



}
